
package org.sql.apachederbylib.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.sql.apachederbylib.exception.ConnectionErrorException;
import org.sql.apachederbylib.exception.NoDriverFoundException;

/**
 *
 * @author Víctor Escobar
 */
public class Connect {
    
    /**
     * This method connect using the Apache Derby driver for Java.
     * @param db the name of the db that you want to connect it.
     * @param create if you want create this database,this flag must be true,false in otherwise.
     * @return A Connection resource.
     * @throws NoDriverFoundException This happen if you don't add the driver jar file into the application PATH.
     * @throws ConnectionErrorException This happen if has been an error while we are doing the connection.
     */
    public static Connection connect(String db,boolean create) throws NoDriverFoundException, ConnectionErrorException{
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            String url="jdbc:derby:db/"+db+";";
            if(create){
                url+="create=true";
            }
            return DriverManager.getConnection(url);
        } catch (ClassNotFoundException ex) {
            throw new NoDriverFoundException("Driver not found,please;are you sure that you add the driver to the PATH?");
        }
        catch (SQLException ex) {
            throw new ConnectionErrorException("The connection did not had been successful");
        }
    }
    
    /**
     * This method disconnect the database,doing a commit before disconnect.
     * @param conn The connection resource give by connect method.
     * @return true if the disconnection has been successful,false in otherwise.
     */
    public static boolean disconnect(Connection conn){
        try{
            conn.commit();
            conn.close();
            return true;
        }catch(SQLException ex){
            return false;
        }
    }
}
